package com.kedsoft.andaily.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.io.ByteStreams;
import com.kedsoft.andaily.common.MessageResult;
import com.kedsoft.andaily.entity.Datum;
import com.kedsoft.andaily.service.DatumService;
import com.kedsoft.andaily.vo.PageVo;
import com.kedsoft.andaily.vo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2019-04-16
 */
@Controller
@RequestMapping("/datum")
public class DatumController extends BaseController{

    private ResourceLoader resourceLoader;

    @Autowired
    DatumService datumService;

    @RequestMapping("index")
    public String index(){
        return "datum/index";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Datum> getPageList(Pagination pagination, @RequestParam(required = false) String name){
        EntityWrapper<Datum> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("name",name);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Datum> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        datumService.selectPage(page,entityWrapper);
        PageVo<Datum> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "form")
    public String form(){
        return "datum/form";
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(HttpServletRequest request,Datum param, @RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return MessageResult.getError("500","上传失败，请选择文件");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        ServletContext application = request.getServletContext();
        String savePath = "C:\\picture\\";
        // 文件保存目录URL
        String saveUrl = request.getContextPath()+"/files/";
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            return MessageResult.getError("500","上传目录不存在。");
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            return MessageResult.getError("500","上传目录没有写权限。");
        }

        String dirName = getDirName(extMap,fileExt);
        // 创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 检查扩展名

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        param.setUrl(saveUrl + newFileName);
        try {
            ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile));
            datumService.insert(param);
            return MessageResult.getSuccess("添加数据成功");
        } catch (Exception e) {
            return MessageResult.getError("500","添加数据失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public MessageResult update(Datum param){
        datumService.updateById(param);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(@RequestParam Integer ids){
        datumService.deleteById(ids);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids){
        String[] id = ids.split(",");
        for (String i: id) {
            Integer intId = Integer.parseInt(i);
            datumService.deleteById(intId);
        }
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "search")
    public String search(){
        return "datum/search";
    }

    private String getDirName(HashMap<String, String> map,String ext){
        for(String key:map.keySet()){
            String value = map.get(key);
            boolean status = value.contains(ext);
            if(status){
                return key;
            }
        }
        return "file";
    }
}

